<template>
  <el-dialog
    :title="isEdit ? '编辑用户' : '新增用户'"
    v-model="dialogVisible"
    width="600px"
    @closed="resetForm"
    :close-on-click-modal="false"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="100px"
      :hide-required-asterisk="false"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" :disabled="isEdit" placeholder="请输入用户名" />
      </el-form-item>
      
      <el-form-item label="姓名" prop="full_name">
        <el-input v-model="form.full_name" placeholder="请输入姓名" />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱地址" />
      </el-form-item>
      
      <el-form-item label="角色" prop="role">
        <el-radio-group v-model="form.role">
          <el-radio label="user">普通用户</el-radio>
          <el-radio label="admin">管理员</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="状态" prop="disabled">
        <el-radio-group v-model="form.disabled">
          <el-radio :label="false">启用</el-radio>
          <el-radio :label="true">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="密码" prop="password" v-if="!isEdit">
        <el-input v-model="form.password" type="password" show-password placeholder="请输入密码" />
      </el-form-item>
      
      <el-form-item label="修改密码" v-else>
        <el-button type="primary" size="small" @click="showPasswordReset = true">重置密码</el-button>
        <span class="password-tip">如需更改密码，请点击重置按钮</span>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
    
    <!-- 重置密码对话框 -->
    <el-dialog
      title="重置密码"
      v-model="showPasswordReset"
      width="500px"
      append-to-body
    >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="120px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input 
            v-model="passwordForm.password" 
            type="password" 
            show-password 
            placeholder="请输入新密码" 
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirm_password">
          <el-input 
            v-model="passwordForm.confirm_password" 
            type="password" 
            show-password 
            placeholder="请确认新密码" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showPasswordReset = false">取消</el-button>
        <el-button type="primary" @click="handleResetPassword" :loading="passwordLoading">确定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, watch, defineExpose, nextTick } from 'vue';
import { ElMessage, ElForm } from 'element-plus';
import { createUser, updateUser } from '@/api/user';

// 定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
});

// 定义组件事件
const emit = defineEmits(['update:visible', 'success']);

// 对话框可见状态
const dialogVisible = ref(false);

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
const passwordFormRef = ref<InstanceType<typeof ElForm>>();

// 加载状态
const loading = ref(false);
const passwordLoading = ref(false);

// 显示重置密码对话框
const showPasswordReset = ref(false);

// 表单数据
const form = reactive({
  _id: '',
  username: '',
  full_name: '',
  email: '',
  role: 'user',
  disabled: false,
  password: ''
});

// 密码重置表单
const passwordForm = reactive({
  password: '',
  confirm_password: ''
});

// 密码匹配验证
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== passwordForm.password) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  full_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度应为6-30个字符', trigger: 'blur' }
  ]
};

// 密码重置校验规则
const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度应为6-30个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val;
});

// 监听dialogVisible变化
watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val);
});

// 监听formData变化
watch(() => props.formData, (val) => {
  if (val) {
    // 复制属性到表单中
    Object.keys(val).forEach(key => {
      if (key in form) {
        (form as any)[key] = val[key];
      }
    });
  }
}, { immediate: true, deep: true });

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      
      try {
        let res;
        
        if (props.isEdit) {
          // 编辑用户 - 不包含密码字段
          const { password, _id, ...updateData } = form;
          res = await updateUser(_id, updateData);
        } else {
          // 创建新用户
          res = await createUser(form);
        }
        
        if (res.code === 200) {
          ElMessage.success(props.isEdit ? '更新成功' : '创建成功');
          emit('success');
          dialogVisible.value = false;
        } else {
          ElMessage.error(res.message || (props.isEdit ? '更新失败' : '创建失败'));
        }
      } catch (error) {
        console.error(props.isEdit ? '更新用户错误:' : '创建用户错误:', error);
        ElMessage.error(props.isEdit ? '更新用户失败' : '创建用户失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 重置密码
const handleResetPassword = async () => {
  if (!passwordFormRef.value) return;
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true;
      
      try {
        const res = await updateUser(form._id, { password: passwordForm.password });
        
        if (res.code === 200) {
          ElMessage.success('密码重置成功');
          showPasswordReset.value = false;
        } else {
          ElMessage.error(res.message || '密码重置失败');
        }
      } catch (error) {
        console.error('重置密码错误:', error);
        ElMessage.error('重置密码失败');
      } finally {
        passwordLoading.value = false;
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }
  showPasswordReset.value = false;
};

// 暴露方法
defineExpose({
  resetForm
});
</script>

<style lang="scss" scoped>
.password-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}
</style>